package com.tfswx.ruleengine.compute.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tfswx.ruleengine.compute.bean.FormDataObject;
import com.tfswx.ruleengine.compute.bean.Mxstgx;
import com.tfswx.ruleengine.compute.bean.RuleInfo;
import com.tfswx.ruleengine.compute.dto.AkFormDataGetInputDTO;
import com.tfswx.ruleengine.compute.dto.DataByBmsahGetInputDTO;
import com.tfswx.ruleengine.compute.dto.ModelBaseInfoGetOutputDTO;
import com.tfswx.ruleengine.compute.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ricky
 * @date 2021/8/19
 */
@Slf4j
public class ExternalUtil {
    private ExternalUtil() {
    }

    public static List<FormDataObject> getDataByBmsah(DataByBmsahGetInputDTO dataByBmsahGetInputDTO) {
        String bmsah = dataByBmsahGetInputDTO.getBmsah();

        String sjmxbm = dataByBmsahGetInputDTO.getSjmxbm();
        if (StringUtils.isBlank(sjmxbm)) {
            sjmxbm = getSjmxbmBybmsah(dataByBmsahGetInputDTO.getTyywHost(), bmsah);
        }

        List<RuleInfo> ruleInfos = dataByBmsahGetInputDTO.getRuleInfos();

        // 通过规则列表获取表名集合
        List<String> tyywStbmjh = getTyywTableList(ruleInfos);

        List<Mxstgx> mxstgxList = dataByBmsahGetInputDTO.getMxstgxList();
        if (mxstgxList == null) {
            mxstgxList = new ArrayList<>();
        }
        String finalSjmxbm = sjmxbm;
        mxstgxList = mxstgxList.stream().filter(item -> item.getMxbm().equals(finalSjmxbm)).collect(Collectors.toList());

        // 通过单位编码获取部门受案号
        String dwbm = getDwbmByBmsah(bmsah);

        AkFormDataGetInputDTO akFormDataGetInputDTO = new AkFormDataGetInputDTO();
        akFormDataGetInputDTO.setDwbm(dwbm);
        akFormDataGetInputDTO.setSjmxbm(sjmxbm);
        akFormDataGetInputDTO.setStbmjh(tyywStbmjh);
        akFormDataGetInputDTO.setXtbs("TYAK");
        Map<String, Object> map = new HashMap<>(1);
        map.put("bmsah", bmsah);
        akFormDataGetInputDTO.setZbZjMap(map);
        akFormDataGetInputDTO.setZjMap(map);
        akFormDataGetInputDTO.setEntityRelationInfoList(mxstgxList);

        log.info("getAkFormData接口入参：{}", JSONObject.toJSONString(akFormDataGetInputDTO, SerializerFeature.DisableCircularReferenceDetect));
        return getAkFormData(dataByBmsahGetInputDTO.getTyywHost(), dataByBmsahGetInputDTO.getAkUrl(), akFormDataGetInputDTO);
    }

    private static String getSjmxbmBybmsah(String host, String bmsah) {
        // 通过单位编码获取部门受案号
        String dwbm = getDwbmByBmsah(bmsah);

        JSONObject caseBaseInfo = getCaseBaseInfo(host, bmsah);

        if (caseBaseInfo == null) {
            throw new AppException("没有获取到案件信息，请检查统一业务配置");
        }

        String mxbm = caseBaseInfo.getString("ajmxbm");
        // 获取数据模型编码
        List<ModelBaseInfoGetOutputDTO> dataModelInfoList = getDataModelInfo(host, dwbm, mxbm);
        if (dataModelInfoList == null || dataModelInfoList.isEmpty()) {
            throw new AppException("未查询到数据模型编码");
        }
        return dataModelInfoList.get(0).getSjmxbm();
    }

    private static List<String> getStbmjh(List<RuleInfo> ruleInfos) {
        Set<String> stbmjh = new HashSet<>();
        for (RuleInfo ruleInfo : ruleInfos) {
            List<String> bmList = ruleInfo.getGzdy().getBmList();
            stbmjh.addAll(bmList);
        }
        return new ArrayList<>(stbmjh);
    }

    private static String getDwbmByBmsah(String bmsah) {
        int i = bmsah.length() - 13;
        return bmsah.substring(i, i + 6);
    }

    private static String getHost(String host) {
        return "http://" + host.replaceAll("https?://", "");
    }

    private static List<FormDataObject> getAkFormData(String host, String akUrl, AkFormDataGetInputDTO akFormDataGetInputDTO) {
        if (StringUtils.isBlank(akUrl)) {
            akUrl = "/gzjy-service/api/modelData/getAkFormData";
        }
        String url = getHost(host) + akUrl;
        JSONObject response = HttpUtil.postForObject(url, akFormDataGetInputDTO, JSONObject.class);
        return TyywHttpUtil.getList(response, FormDataObject.class);
    }

    // 获取数据模型编码
    private static List<ModelBaseInfoGetOutputDTO> getDataModelInfo(String host, String dwbm, String mxbm) {
        String url = getHost(host) + "/ajmx-service/api/model/getModelBaseInfo";
        JSONObject param = new JSONObject();
        param.put("dwbm", dwbm);
        param.put("mxbm", mxbm);
        JSONObject response = HttpUtil.postForObject(url, param, JSONObject.class);
        return TyywHttpUtil.getList(response, ModelBaseInfoGetOutputDTO.class);
    }

    // 获取案件模型编码
    private static JSONObject getCaseBaseInfo(String host, String bmsah) {
        String url = getHost(host) + "/ajmx-service/api/caseCommon/getCaseBaseInfo";
        JSONObject param = new JSONObject();
        param.put("bmsah", bmsah);
        JSONObject response = HttpUtil.postForObject(url, param, JSONObject.class);
        return TyywHttpUtil.getObject(response, JSONObject.class);
    }

    public static List<String> getTyywTableList(List<RuleInfo> ruleInfos) {
        List<String> stbmjh = getStbmjh(ruleInfos);
        return stbmjh.stream().filter(TyywTableNameUtil::isTyywTable).collect(Collectors.toList());
    }

    public static void main(String[] args) {

        DataByBmsahGetInputDTO dataByBmsahGetInputDTO = new DataByBmsahGetInputDTO();
        dataByBmsahGetInputDTO.setBmsah("汉东检刑诉受[2021]980000000714号");
        dataByBmsahGetInputDTO.setTyywHost("192.168.3.50:8080");
        dataByBmsahGetInputDTO.setAkUrl("/ajmx-service/api/caseForm/getAkFormData");
        dataByBmsahGetInputDTO.setRuleInfos(new ArrayList<>());
        List<FormDataObject> dataByBmsah = getDataByBmsah(dataByBmsahGetInputDTO);
        System.out.println(dataByBmsah);
    }
}
